﻿using Abp.Dapper;
using Abp.Domain.Uow;
using Abp.EntityFrameworkCore.Configuration;
using Abp.Modules;
using Abp.Reflection.Extensions;
using Abp.Zero.EntityFrameworkCore;
using System.Collections.Generic;
using System.Reflection;
using ZCMS.EntityFrameworkCore.Seed;
using Abp.Configuration.Startup;


namespace ZCMS.EntityFrameworkCore
{
    [DependsOn(
        typeof(ZCMSCoreModule), 
        typeof(AbpZeroCoreEntityFrameworkCoreModule),
		typeof(AbpDapperModule)
	)]
    public class ZCMSEntityFrameworkModule : AbpModule
    {
        /* Used it tests to skip dbcontext registration, in order to use in-memory database of EF Core */
        public bool SkipDbContextRegistration { get; set; }

        public bool SkipDbSeed { get; set; }

        public override void PreInitialize()
        {
			Configuration.ReplaceService<IConnectionStringResolver, MyConnectionStringResolver>();

			if (!SkipDbContextRegistration)
            {
				//注册第一个数据库
                Configuration.Modules.AbpEfCore().AddDbContext<ZCMSDbContext>(options =>
                {
                    if (options.ExistingConnection != null)
                    {
                        ZCMSDbContextConfigurer.Configure(options.DbContextOptions, options.ExistingConnection);
                    }
                    else
                    {
                        ZCMSDbContextConfigurer.Configure(options.DbContextOptions, options.ConnectionString);
                    }
                });
            }

			//注册第二个数据库
			Configuration.Modules.AbpEfCore().AddDbContext<RWDBDbContext > (options =>
			{
				if (options.ExistingConnection != null)
				{
					RWDBDbContextOptionsConfigurer.Configure(options.DbContextOptions, options.ExistingConnection);
				}
				else
				{
					RWDBDbContextOptionsConfigurer.Configure(options.DbContextOptions, options.ConnectionString);
				}
			});

		}

        public override void Initialize()
        {
            IocManager.RegisterAssemblyByConvention(typeof(ZCMSEntityFrameworkModule).GetAssembly());
			DapperExtensions.DapperExtensions.SetMappingAssemblies(new List<Assembly> { typeof(ZCMSEntityFrameworkModule).GetAssembly() });
		}

        public override void PostInitialize()
        {
            if (!SkipDbSeed)
            {
                SeedHelper.SeedHostDb(IocManager);
            }
        }
    }
}
